<template>
  <div style="margin-top: 10px" v-loading="fullloading">
    <div style="margin-bottom: 10px;display: flex;justify-content: center;align-items: center">
      <el-input
        placeholder="请输入用户名..."
        prefix-icon="el-icon-search"
        size="small"
        style="width: 400px;margin-right: 10px;"
        v-model="keywords">
      </el-input>
      <el-button size="small" type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
      <el-button size="small" type="primary" icon="el-icon-add" @click="addClick">新增</el-button>
    </div>
    <div style="display: flex;justify-content: space-around;flex-wrap: wrap;text-align: left">
      <el-card style="width: 350px;margin-bottom: 20px" v-for="(item,index) in hrs" :key="item.id"
               v-loading="cardLoading[index]">
        <div slot="header" class="clearfix">
          <span>{{item.name}}</span>
          <el-button type="text"
                     style="color: #f6061b;margin: 0px;float: right; padding: 3px 0;width: 15px;height:15px"
                     icon="el-icon-delete" @click="deleteHr(item.id, item.name)" title="删除"></el-button>
         <el-button type="text"
                     style="color: #409EFF;margin-right: 10px;float: right; padding: 3px 0;width: 15px;height:15px"
                     icon="el-icon-info" @click="resetPwd(item.id, item.name)" title="密码重置"></el-button>
          <el-button type="text"
                     style="color: #409EFF;margin-right: 0px;float: right; padding: 3px 0;width: 15px;height:15px"
                     icon="el-icon-edit" @click="updateHr(item.id)" title="编辑"></el-button>
        </div>
        <div>
          <div style="width: 100%;display: flex;justify-content: center">
            <el-popover
            placement="right"
            width="400"
            trigger="click">
            <img :src="item.userface" alt="item.name" style="width: 400px;height: 400px; border-radius: 5px">
            <img :src="item.userface" slot="reference" alt="item.name" style="width: 70px;height: 70px;border-radius: 70px">
          </el-popover>
          </div>
          <div style="margin-top: 20px">
            <div><span class="user-info"><b>登录ID:</b>{{item.username}}</span></div>
            <div><span class="user-info"><b>用户名:</b>{{item.name}}</span></div>
            <div><span class="user-info"><b>手机号码:</b>{{item.phone}}</span></div>
            <div><span class="user-info"><b>地址:</b>{{item.address}}</span></div>
            <div class="user-info" style="display: flex;align-items: center;margin-bottom: 3px">
              <b>用户状态:</b>
              <el-switch
                style="display: inline;margin-left: 5px"
                v-model="item.enabled"
                active-color="#13ce66"
                inactive-color="#aaaaaa"
                active-text="启用"
                :key="item.id"
                @change="switchChange(item.enabled,item.id,index)"
                inactive-text="禁用">
              </el-switch>
            </div>
            <div class="user-info">
              <b>用户角色:</b>
              <el-tag
                v-for="role in item.roles"
                :key="role.id"
                type="success"
                size="mini"
                style="margin-right: 5px"
                :disable-transitions="false">{{role.nameZh}}
              </el-tag>
              <el-popover
                v-loading="eploading[index]"
                placement="right"
                title="角色列表"
                width="200"
                @hide="updateHrRoles(item.id,index)"
                :key="item.id"
                trigger="click">
                <el-select v-model="selRoles" multiple placeholder="请选择角色">
                  <el-option
                    v-for="ar in allRoles"
                    :key="ar.id"
                    :label="ar.nameZh"
                    :value="ar.id">
                  </el-option>
                </el-select>
                <el-button type="text" icon="el-icon-more" style="color: #09c0f6;padding-top: 0px" slot="reference"
                           @click="loadSelRoles(item.roles,index)" :disabled="moreBtnState"></el-button>
              </el-popover>
            </div>
            <div><span class="user-info"><b>职位:</b>{{item.positionName}}</span></div>
          </div>
        </div>
      </el-card>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[6, 12, 24, 36]"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    
    <!-- 用户编辑 新增 -->
    <el-dialog
        :title="dialogTitle"
        style="padding: 0px;"
        :close-on-click-modal="false"
        :visible.sync="dialogVisible"
        width="50%"
        @close="dialogClose"
        >
        <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="120px" label-position="right" size="mini">
          <el-form-item label="登录ID：" prop="username" required="true">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="用户名：" prop="name" required="true">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="电话号码：" prop="phone" required="true">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-row>
              <el-col :span="12">
                <el-form-item label="性别：" prop="gender" required="true"  style="text-align: left;">
                  <el-radio-group v-model="form.gender">
                    <el-radio style="margin-left: 15px" label="1">男</el-radio>
                    <el-radio style="margin-left: 15px" label="0">女</el-radio>
                    <el-radio style="margin-left: 15px" label="2">其他</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期：" prop="birthday">
                  <el-col :span="24">
                    <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="form.birthday" style="width: 100%;"></el-date-picker>
                  </el-col>
                </el-form-item>
              </el-col>
          </el-row>
          <el-form-item label="密码" prop="password" required="true" v-if="form.id == ''">
            <el-input type="password" v-model="form.password"  auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass" required="true" v-if="form.id == ''">
            <el-input type="password" v-model="form.checkPass" auto-complete="off"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
                <el-form-item label="所属部门:" prop="departmentId" required="true">
                  <el-popover
                    v-model="showOrHidePop"
                    placement="right"
                    title="请选择部门"
                    trigger="manual">
                    <el-tree :data="deps" :default-expand-all="true" :props="defaultProps" :expand-on-click-node="false"
                              @node-click="handleNodeClick"></el-tree>
                    <div slot="reference"
                          style="width: 90%;height: 26px;font-size:13px;border: 1px;border-radius: 5px;border-style: solid;padding-left: 13px;box-sizing:border-box;border-color: #dcdfe6;cursor: pointer;"
                          @click.left="showDepTree" v-bind:style="{color: depTextColor}">{{form.departmentName}}
                    </div>
                  </el-popover>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="职位:" prop="positionId" required="true">
                <el-select v-model="form.positionId" clearable @clear="clearSelect" placeholder="请选择" size="mini" required="true">
                    <el-option
                    v-for="item in positionList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
                </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="联系地址：" prop="address">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-form-item>
          <el-form-item size="small">
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <el-button @click="resetForm">重 置</el-button>
          </el-form-item>
        </el-form>
    </el-dialog>
    </div>
</template>
<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入人员登录名"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      var phone = /^1[3|4|5|7|8]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入电话号码"));
      } else if (!phone.test(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    };
    return {
      keywords: "",
      dialogVisible: false,
      formLoading: false,
      dialogTitle: "人员基本信息编辑",
      fullloading: false,
      hrs: [],
      cardLoading: [],
      eploading: [],
      allRoles: [],
      moreBtnState: false,
      selRoles: [],
      selRolesBak: [],
      deps: [],
      positionList: [],
      defaultProps: {
        label: "name",
        isLeaf: "leaf",
        children: "children"
      },
      depTextColor: "#c0c4cc",
      showOrHidePop: false,
      form: {
        id: "",
        name: "",
        username: "",
        phone: "",
        password: "",
        gender: "",
        birthday: "",
        address: "",
        remark: "",
        departmentName: "",
        departmentId: "",
        positionId: "",
        enabled: false
      },
      currentPage: 1,
      pageSize: 6,
      total: 0,
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        name: [
          { required: true, message: "请输入人员名称", trigger: "blur" },
          { min: 2, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ],
        phone: [{ validator: validatePhone, trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
        departmentId: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        positionId: [
          { required: true, message: "请选择职位", trigger: "blur" }
        ],
        password: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }]
      }
    };
  },
  mounted: function() {
    this.initCards(true);
    this.loadAllRoles();
    this.initDeps();
    this.initPositions();
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.initCards();
    },
    clearSelect() {
      this.form.positionId = "";
    },
    dialogClose() {
      this.showOrHidePop = false;
    },
    handleCurrentChange(val) {
      this.initCards();
    },
    searchClick() {
      this.initCards(true);
      this.loadAllRoles();
    },
    addClick() {
      this.dialogVisible = true;
      this.resetForm();
    },
    submitForm() {
      var _this = this;
      var id = this.form.id;
      this.$refs["form"].validate(valid => {
        if (valid) {
          var param = _this.form;
          var url;
          this.formLoading = true;
          var request;
          var flag = false;
          if (id == "") {
            url = "/system/hr/add";
            request = this.postRequest;
            flag = true;
          } else {
            url = "/system/hr/";
            request = this.putRequest;
            flag = false;
          }
          request(url, param).then(resp => {
            _this.formLoading = false;
            if (resp && resp.status == 200) {
              var respData = resp.data;
              _this.$message({ type: respData.status, message: respData.msg });
              _this.dialogVisible = false;
              _this.initCards(flag);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs["form"].resetFields();
      this.form.id = "";
      this.form.departmentName = "";
      this.form.departmentId = "";
    },
    showDepTree() {
      this.showOrHidePop = !this.showOrHidePop;
    },
    handleNodeClick(data) {
      this.form.departmentName = data.name;
      this.form.departmentId = data.id;
      this.showOrHidePop = false;
      this.depTextColor = "#606266";
      this.$refs["form"].validateField("departmentId");
    },
    initDeps() {
      var _this = this;
      this.getRequest("/system/basic/dep/-1").then(resp => {
        if (resp && resp.status == 200) {
          var data = resp.data;
          _this.deps = data;
        }
      });
    },
    initPositions() {
      var _this = this;
      this.getRequest("/system/basic/positions").then(resp => {
        if (resp && resp.status == 200) {
          var data = resp.data;
          _this.positionList = data;
        }
      });
    },
    updateHrRoles(hrId, index) {
      this.moreBtnState = false;
      var _this = this;
      if (this.selRolesBak.length == this.selRoles.length) {
        for (var i = 0; i < this.selRoles.length; i++) {
          for (var j = 0; j < this.selRolesBak.length; j++) {
            if (this.selRoles[i] == this.selRolesBak[j]) {
              this.selRolesBak.splice(j, 1);
              break;
            }
          }
        }
        if (this.selRolesBak.length == 0) {
          return;
        }
      }
      this.eploading.splice(index, 1, true);
      this.putRequest("/system/hr/roles", {
        hrId: hrId,
        rids: this.selRoles
      }).then(resp => {
        _this.eploading.splice(index, 1, false);
        if (resp && resp.status == 200) {
          var data = resp.data;
          _this.$message({ type: data.status, message: data.msg });
          if (data.status == "success") {
            _this.refreshHr(hrId, index);
          }
        }
      });
    },
    refreshHr(hrId, index) {
      var _this = this;
      _this.cardLoading.splice(index, 1, true);
      this.putRequest("/system/hr/id/" + hrId).then(resp => {
        _this.cardLoading.splice(index, 1, false);
        _this.hrs.splice(index, 1, resp.data);
      });
    },
    loadSelRoles(hrRoles, index) {
      this.moreBtnState = true;
      this.selRoles = [];
      this.selRolesBak = [];
      hrRoles.forEach(role => {
        this.selRoles.push(role.id);
        this.selRolesBak.push(role.id);
      });
    },
    loadAllRoles() {
      var _this = this;
      _this.fullloading = true;
      this.getRequest("/system/basic/roles").then(resp => {
        _this.fullloading = false;
        if (resp && resp.status == 200) {
          _this.allRoles = resp.data;
        }
      });
    },
    switchChange(newValue, hrId, index) {
      var _this = this;
      _this.cardLoading.splice(index, 1, true);
      this.putRequest("/system/hr/", {
        enabled: newValue,
        id: hrId
      }).then(resp => {
        _this.cardLoading.splice(index, 1, false);
        if (resp && resp.status == 200) {
          var data = resp.data;
          _this.$message({ type: data.status, message: data.msg });
          if (data.status == "error") {
            _this.refreshHr(hrId, index);
          }
        } else {
          _this.refreshHr(hrId, index);
        }
      });
    },
    initTotal() {
      this.fullloading = true;
      var _this = this;
      var searchWords;
      if (this.keywords === "") {
        searchWords = "all";
      } else {
        searchWords = this.keywords;
      }
      this.getRequest("/system/hr/getHrsByKeywordsCount/" + searchWords).then(
        resp => {
          this.fullloading = false;
          if (resp && resp.status == 200) {
            _this.total = resp.data;
          }
        }
      );
    },
    initCards(flag) {
      if (flag === true) {
        this.initTotal();
      }
      this.fullloading = true;
      var _this = this;
      var searchWords;
      if (this.keywords === "") {
        searchWords = "all";
      } else {
        searchWords = this.keywords;
      }
      var start = this.pageSize * (this.currentPage - 1);
      var param =
        "?keywords=" +
        searchWords +
        "&start=" +
        start +
        "&pageSize=" +
        this.pageSize;
      this.getRequest("/system/hr/keywords" + param).then(resp => {
        this.fullloading = false;
        if (resp && resp.status == 200) {
          _this.hrs = resp.data;
          var length = resp.data.length;
          _this.cardLoading = Array.apply(null, Array(length)).map(function(
            item,
            i
          ) {
            return false;
          });
          _this.eploading = Array.apply(null, Array(length)).map(function(
            item,
            i
          ) {
            return false;
          });
        }
      });
    },
    deleteHr(hrId, name) {
      var _this = this;
      this.$confirm("是否删除[" + name + "]用户!", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.fullloading = true;
          this.deleteRequest("/system/hr/" + hrId).then(resp => {
            _this.fullloading = false;
            if (resp && resp.status == 200) {
              var data = resp.data;
              _this.$message({ type: data.status, message: data.msg });
              if (data.status == "success") {
                _this.initCards(true);
                _this.loadAllRoles();
              }
            }
          });
        })
        .catch(() => {
          _this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    resetPwd(hrId, name) {
      var _this = this;
      this.$confirm(
        "是否重置[" + name + "]用户的密码，重置以后密码为“123456”",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.fullloading = true;
          this.putRequest("/system/hr/resetPassword/" + hrId).then(resp => {
            _this.fullloading = false;
            if (resp && resp.status == 200) {
              var data = resp.data;
              _this.$message({ type: data.status, message: data.msg });
            }
          });
        })
        .catch(() => {
          _this.$message({
            type: "info",
            message: "已取消重置密码"
          });
        });
    },
    updateHr(hrId) {
      var _this = this;
      this.fullloading = true;
      this.dialogVisible = true;
      this.formLoading = true;
      this.getRequest("/system/hr/getByUserId/" + hrId).then(resp => {
        _this.fullloading = false;
        _this.formLoading = false;
        _this.pDisabled = true;
        if (resp && resp.status == 200) {
          var data = resp.data;
          _this.form.id = data.id;
          _this.form.name = data.name;
          _this.form.username = data.username;
          _this.form.phone = data.phone;
          _this.form.gender = data.gender + "";
          _this.form.birthday = data.birthday + "";
          _this.form.address = data.address;
          _this.form.remark = data.remark;
          _this.form.departmentName = data.departmentName;
          _this.form.departmentId = data.departmentId;
          _this.form.positionId = data.positionId;
          _this.form.enabled = data.enabled;
        }
      });
    }
  }
};
</script>
<style>
.user-info {
  font-size: 12px;
  color: #09c0f6;
}
.user-info b {
  display: inline-flex;
  width: 80px;
  margin-right: 10px;
  justify-content: flex-end;
}
</style>
